<?php
namespace app\index\controller;

use app\index\model\UserModel;
use think\facade\Config;
use think\Controller;
use think\Db;
use think\Request;

class Wechat extends Controller
{
    private $wx_appid = '';
    private $wx_appsecret = '';


    public function __construct()
    {
        parent::__construct();
        $this->wx_appid = Config::get('service.wx.appid');
        $this->wx_appsecret = Config::get('service.wx.appsecret');
    }


    public function callback(Request $request)
    {
        $postStr = file_get_contents('php://input');
        if(!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $post_arr = json_decode(json_encode($postObj), true);
            if(isset($post_arr['MsgType']) && $post_arr['MsgType'] == 'event' && $post_arr['Event'] == 'subscribe'){
                if(isset($post_arr['EventKey']) && !empty($post_arr['EventKey'])){
                    $EventKey = explode("_",$post_arr['EventKey']);
                    $this->updUserinfo($post_arr['FromUserName'],$EventKey[1]);
                }
            }
        }
        exit();
    }


    function updUserinfo($openid, $userid=0){
        $this->getWechatAccessToken();
        $access_token = $this->getTxtAccessToken();
        $u_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
        $user_info = curl_get_sub($u_url);

        //判断当前openid是否已经绑定  如已绑定 取消之前的绑定
        $existArr = UserModel::where(['wx_openid'=>$user_info['openid']])->column('id');
        if($existArr){
            UserModel::where('id','in',$existArr)->update([
                'wx_openid' => '',
                'wx_nickname' => '',
                'wx_headimgurl' => '',
                'wx_bangdt' => '',
            ]);
        }

        UserModel::where(['id'=>$userid])->update([
            'wx_openid' => $user_info['openid'],
            'wx_nickname' => $user_info['nickname'],
            'wx_headimgurl' => $user_info['headimgurl'],
            'wx_bangdt' => date("Y年m月d日 H:i"),
        ]);
        return true;
    }



    //生成关注二维码
    public function create_qrcode($userid=0){
        $this->getWechatAccessToken();
        $access_token = $this->getTxtAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$access_token;
        $post_json = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id":'.$userid.'}}}';
        $info = curl_post_sub($url, $post_json);
        $qrcode_url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$info['ticket'];
        return $qrcode_url;
    }



    public function getWechatAccessToken(){
        $acc_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->wx_appid."&secret=".$this->wx_appsecret;
        $acc_info = curl_get_sub($acc_url);

        if(isset($acc_info['access_token'])){
            file_put_contents('wx_access_token.txt',$acc_info['access_token']);
        }
    }
    public function getTxtAccessToken(){
      $file_name = 'wx_access_token.txt';
      $access_token = file_get_contents($file_name);
      return $access_token;
    }


}
